package pl.tssoft.math.core.calculation.operator;

import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import pl.tssoft.math.core.calculation.operator.builtin.ColonOperator;
import pl.tssoft.math.core.calculation.operator.builtin.DivideOperator;
import pl.tssoft.math.core.calculation.operator.builtin.MultiplyOperator;
import pl.tssoft.math.core.calculation.operator.builtin.PlusOperator;
import pl.tssoft.math.core.calculation.operator.builtin.PowerOperator;
import pl.tssoft.math.core.calculation.operator.builtin.TransposeOperator;
import pl.tssoft.math.core.exceptions.InternalException;

/**
 *
 * @author tomasz.serafin
 */
public class OperatorFactory {

    private static final Map<String, Class> OPERATOR_CLASS_MAP = new HashMap<String, Class>() {
        {
            put("+", PlusOperator.class);
            put("-", PlusOperator.class);
            put("*", MultiplyOperator.class);
            put("/", DivideOperator.class);
            put("^", PowerOperator.class);
            put("'", TransposeOperator.class);
            put(":", ColonOperator.class);
        }
    };

    public static Operator create(String operatorString) throws NoSuchElementException {

        Class c = OPERATOR_CLASS_MAP.get(operatorString);
        if (c == null) {
            throw new NoSuchElementException("no class for operator: " + operatorString);
        }
        try {
            return (Operator) c.getConstructor().newInstance();
        } catch (Exception ex) {
            throw new InternalException("error while initializing operator: " + operatorString, ex);
        }
    }
}
